<template>
  <div class="post-comment">
    <van-field
      class="post-field"
      v-model.trim="inputComment"
      rows="2"
      autosize
      type="textarea"
      maxlength="50"
      placeholder="优质评论将会被优先展示"
      show-word-limit
    />
    <van-button
      type="primary"
      size="small"
      @click="addComments"
      :disabled="!inputComment.length"
      >发布</van-button
    >
  </div>
</template>

<script>
import { postComments } from '@/api/common';
export default {
  name: 'PostComment',
  components: {},
  props: {
    target: {
      type: [Number, Object, String],
      require: true
    }
  },
  data () {
    return {
      inputComment: ''
    };
  },
  computed: {},
  watch: {},
  inject: {
    articleId: {
      type: [Number, Object, String],
      default: null
    }
  },
  created () {},
  mounted () {},
  methods: {
    async addComments () {
      try {
        this.$toast.loading({
          message: '发布中...',
          forbidClick: true,
          duration: 0
        });
        const { data } = await postComments({
          target: this.target.toString(), // 评论的目标id（评论文章即为文章id，对评论进行回复则为评论id）
          content: this.inputComment, // 评论内容
          art_id: this.articleId ? this.articleId.toString() : null // 文章id，对评论内容发表回复时，需要传递此参数，表明所属文章id。对文章进行评论，不要传此参数。
        });
        // 关闭弹出层
        // 将发布内容置顶到评论顶部
        this.$emit('addCommentSuccess', data.data);
        // 清空输入框
        this.inputComment = '';
        this.$toast.success('发布成功');
      } catch (error) {
        this.$toast('发布失败请重试');
      }
    }
  }
};
</script>

<style scoped lang="less">
.post-comment {
  display: flex;
  padding: 15px;
  align-items: flex-end;
  .post-field {
    background: #f5f7f9;
    margin-right: 15px;
  }
}
</style>
